package com.ys.controller.api.base;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bo.dto.NameValueDto;
import com.ys.config.MenuId;
import com.ys.entity.base.TbIncomePay;
import com.ys.entity.base.TbIncomePayItem;
import com.ys.entity.finance.TcwPartnerBankInfo;
import com.ys.entity.sys.TbCompanyBankInfo;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.base.TbIncomePayService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.PdfService;
import com.ys.service.sys.UploadService;
import com.ys.util.DateUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 * 个税付款单
 */
@Controller
@RequestMapping("/api/inter/tbIncomePay")
public class ApiInterTbIncomePayController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTbIncomePayController.class);

    @Autowired
    private CommonApiService<TbIncomePay> commonApiService;

    @Autowired
    private TbIncomePayService tbIncomePayService;

    @Autowired
    private PdfService pdfService;

    @RequiresPermissions("tbIncomePay:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TbIncomePay cond,String conditions){
        String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");

        if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
            cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
        }
        cond.setOrderby("A.createTime DESC")
        .addLeftJoin("YS_ProcInst Ysp ON Ysp.bid = A.bid")//流程表
        .addField("Ysp.updateTime AS updateTime1")
        .addLeftJoin("TB_UserPayApply tbup ON tbup.id = A.UserPayApplyId")//申请表
        .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = tbup.OrgId")//组织机构表
        .addField("O.OrgName AS orgName")//所属公司
        .addField("tbup.bid AS userPayApplyBid")
        .addLeftJoin("TB_CompanyBankInfo cbi ON cbi.id = A.CompanyBankId")//公司银行信息
        .addField("cbi.Vyhzh AS vyhzh,cbi.Vkhh AS vkhh,cbi.Vyhzhmc AS vyhzhmc")
        .addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id")
        .addField("CONCAT(t2.UserId,'/', t2.UserName) as _ys_createUserInfo")
        .addField("t2.DeptName as deptName")
        .addLeftJoin("TCW_PartnerBankInfo pbi ON pbi.id = A.PartnerBankId")//收款人银行
        .addField("pbi.Vyhzh AS hzvyhzh,pbi.Vkhh AS hzvkhh,pbi.Vyhzhmc AS hzvyhzhmc")
        .addField("(SELECT SUM(R.personalTax) FROM TB_UserPaySlip R LEFT JOIN TB_UserPayApplyItem upai ON R.id = upai.UserPaySlipidid LEFT JOIN TB_IncomePayItem ipi ON upai.id = ipi.UserPayApplyItemId WHERE ipi.incomePayBid = a.bid ) personalTax")
        ;
        return commonApiService.searchLay(cond);
    }


    /**
     * 新增
     */
    @RequiresPermissions("tbIncomePay:add")
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            logger.info("个税付款单新增传参：" + params);
            //修改
            return tbIncomePayService.add(params,subData);
        } catch (Exception e) {
            logger.error("个税付款单新增出错：", e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions("tbIncomePay:add")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            logger.info("个税付款单修改传参：" + params);
            //修改
            return tbIncomePayService.edit(params,subData);
        } catch (Exception e) {
            logger.error("个税付款单修改出错：", e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TbIncomePay cond, String conditions) throws Exception{

        cond.setPage(0).setSize(999999);
        String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");

        if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
            cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
        }
        cond.setOrderby("A.createTime DESC")
                .addLeftJoin("YS_ProcInst Ysp ON Ysp.bid = A.bid")//流程表
                .addField("Ysp.updateTime AS updateTime1")
                .addLeftJoin("TB_UserPayApply tbup ON tbup.id = A.UserPayApplyId")//申请表
                .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = tbup.OrgId")//组织机构表
                .addField("O.OrgName AS orgName")//所属公司
                .addField("tbup.bid AS userPayApplyBid")
                .addLeftJoin("TB_CompanyBankInfo cbi ON cbi.id = A.CompanyBankId")//公司银行信息
                .addField("cbi.Vyhzh AS vyhzh,cbi.Vkhh AS vkhh,cbi.Vyhzhmc AS vyhzhmc")
                .addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id")
                .addField("CONCAT(t2.UserId,'/', t2.UserName) as _ys_createUserInfo")
                .addField("t2.DeptName as deptName")
                .addLeftJoin("TCW_PartnerBankInfo pbi ON pbi.id = A.PartnerBankId")//收款人银行
                .addField("pbi.Vyhzh AS hzvyhzh,pbi.Vkhh AS hzvkhh,pbi.Vyhzhmc AS hzvyhzhmc")
                .addField("(SELECT SUM(R.personalTax) FROM TB_UserPaySlip R LEFT JOIN TB_UserPayApplyItem upai ON R.id = upai.UserPaySlipidid LEFT JOIN TB_IncomePayItem ipi ON upai.id = ipi.UserPayApplyItemId WHERE ipi.incomePayBid = a.bid ) personalTax")
        ;
        List<Map<String, Object>> listData = cond.queryMap();


        List<YsCol> listField = new YsCol()
                .setMenuId(MenuId.TB_IncomePay)
                .setFrontShow(YsColEnum.FrontShow.SHOW.value)
                .setOrderby("A.SortNo asc")
                .queryList();

        ExportExcelUtils<TbIncomePay> util = new ExportExcelUtils<TbIncomePay>(new TbIncomePay());

        String toFilePath = util.exportExcel(listData, listField, "个税付款单表");
        UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }


    /**
     * 删除个税付款单
     */
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tbIncomePayService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败，请联系客服");
        }
    }

    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tbIncomePayService.flowPass(id, ShiroUtils.getUserId());
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("服务器正在开小差，请联系客服");
        }
    }

    /**
     * 流转退回
     */
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        try {
            return tbIncomePayService.flowRefuse(id, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("服务器正在开小差，请联系客服");
        }
    }

    /**
     * 流转驳回
     */
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){

        try {
            return tbIncomePayService.flowInit(id, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("服务器正在开小差，请联系客服");
        }
    }


    /**
     * 打印个税付款单
     * @param request
     * @param bid
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportdy")
    @ResponseBody
    public R exportdy(HttpServletRequest request,@RequestParam("bid") String bid) throws Exception{
        TbIncomePay tbIncomePay = new TbIncomePay().setBid(bid).queryFirst();
        //人员信息
        TsUserChange tsUserChange = new TsUserChange().setId(Long.valueOf(tbIncomePay.getCreateChangeId())).queryFirst();
        //付款信息
        TbCompanyBankInfo tbCompanyBankInfo = new TbCompanyBankInfo().setId(tbIncomePay.getCompanyBankId()).queryFirst();

        //收款人
        TcwPartnerBankInfo tcwPartnerBankInfo = new TcwPartnerBankInfo().setId(tbIncomePay.getPartnerBankId()).queryFirst();

        //子件数据
        BigDecimal personalTax = BigDecimal.ZERO;
        List<Map<String, Object>> sonlist = new TbIncomePayItem()
                .setIncomePayBid(bid)
                .addLeftJoin("TB_UserPayApplyItem upai ON upai.id = A.UserPayApplyItemId")//员工申请表详情
                .addLeftJoin("TB_UserPaySlip R ON R.id = upai.UserPaySlipidid")//员工工资表
                .addField("R.personalTax AS personalTax")//个人所得税
                .queryMap();
        for (Map<String, Object> son : sonlist){
            personalTax = personalTax.add(new BigDecimal(son.get("personalTax").toString()));
        }

        List<NameValueDto> listData = new ArrayList<>();
        listData.add(new NameValueDto("单据编号",bid));
        listData.add(new NameValueDto("申请人",tsUserChange.getUserId() + "/" + tsUserChange.getUserName()));
        listData.add(new NameValueDto("申请部门",tsUserChange.getDeptName()));
        listData.add(new NameValueDto("付款账号",tbCompanyBankInfo.getVyhzhmc() + "/" + tbCompanyBankInfo.getVyhzh() + "/" + tbCompanyBankInfo.getVkhh()));
        listData.add(new NameValueDto("收款账号",tcwPartnerBankInfo.getVyhzhmc() + "/" + tcwPartnerBankInfo.getVyhzh() + "/" + tcwPartnerBankInfo.getVkhh()));
        listData.add(new NameValueDto("付款类型",""));
        listData.add(new NameValueDto("付款金额",(personalTax).toString()));
        listData.add(new NameValueDto("付款说明","个人所得税"));
        String url = pdfService.generatePDF(bid,"个税付款单",tbCompanyBankInfo.getVyhzhmc(), DateUtil.getYYYY_MM_DD_HH_mm_ss(tbIncomePay.getCreateTime()),listData);
        return R.ok(url);
    }

}
